import type { ThemeConfig } from 'ant-design-vue/es/config-provider/context'
import { theme } from 'ant-design-vue'

// Design Token 系统 - 设计令牌定义
export const designTokens = {
  // 色彩系统
  colors: {
    // 品牌色
    primary: '#1890ff',
    primaryHover: '#40a9ff',
    primaryActive: '#096dd9',
    
    // 功能色
    success: '#52c41a',
    warning: '#faad14',
    error: '#ff4d4f',
    info: '#1890ff',
    
    // 中性色
    textPrimary: 'rgba(0, 0, 0, 0.88)',
    textSecondary: 'rgba(0, 0, 0, 0.65)',
    textTertiary: 'rgba(0, 0, 0, 0.45)',
    textQuaternary: 'rgba(0, 0, 0, 0.25)',
    
    // 背景色
    bgLayout: '#f0f2f5',
    bgContainer: '#ffffff',
    bgElevated: '#ffffff',
    bgSpotlight: '#ffffff',
    
    // 边框色
    borderSecondary: '#f0f0f0',
    borderPrimary: '#d9d9d9',
    
    // 生命宇宙主题色
    lifeverse: {
      quantum: '#722ed1',      // 量子紫
      neural: '#13c2c2',       // 神经青
      consciousness: '#eb2f96', // 意识粉
      evolution: '#52c41a',    // 进化绿
      cosmic: '#1890ff',       // 宇宙蓝
    }
  },
  
  // 字体系统
  typography: {
    fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif',
    fontSizes: {
      xs: 12,
      sm: 14,
      md: 16,
      lg: 18,
      xl: 20,
      xxl: 24,
      xxxl: 32,
    },
    fontWeights: {
      normal: 400,
      medium: 500,
      semibold: 600,
      bold: 700,
    },
    lineHeights: {
      tight: 1.2,
      normal: 1.5,
      relaxed: 1.8,
    }
  },
  
  // 间距系统
  spacing: {
    xs: 4,
    sm: 8,
    md: 16,
    lg: 24,
    xl: 32,
    xxl: 48,
    xxxl: 64,
  },
  
  // 圆角系统
  borderRadius: {
    none: 0,
    sm: 4,
    md: 6,
    lg: 8,
    xl: 12,
    xxl: 16,
    full: 9999,
  },
  
  // 阴影系统
  shadows: {
    sm: '0 1px 2px rgba(0, 0, 0, 0.03), 0 1px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px rgba(0, 0, 0, 0.02)',
    md: '0 1px 2px rgba(0, 0, 0, 0.03), 0 1px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px rgba(0, 0, 0, 0.02)',
    lg: '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)',
    xl: '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)',
    xxl: '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)',
  },
  
  // 动画系统
  motion: {
    duration: {
      fast: '0.1s',
      normal: '0.2s',
      slow: '0.3s',
    },
    easing: {
      linear: 'linear',
      ease: 'ease',
      easeIn: 'ease-in',
      easeOut: 'ease-out',
      easeInOut: 'ease-in-out',
    }
  }
}

// Ant Design Vue 主题配置
export const themeConfig: ThemeConfig = {
  algorithm: theme.defaultAlgorithm,
  token: {
    // 品牌色
    colorPrimary: designTokens.colors.primary,
    colorSuccess: designTokens.colors.success,
    colorWarning: designTokens.colors.warning,
    colorError: designTokens.colors.error,
    colorInfo: designTokens.colors.info,
    
    // 字体
    fontFamily: designTokens.typography.fontFamily,
    fontSize: designTokens.typography.fontSizes.sm,
    fontSizeLG: designTokens.typography.fontSizes.md,
    fontSizeXL: designTokens.typography.fontSizes.lg,
    
    // 圆角
    borderRadius: designTokens.borderRadius.md,
    borderRadiusLG: designTokens.borderRadius.lg,
    borderRadiusSM: designTokens.borderRadius.sm,
    
    // 间距
    padding: designTokens.spacing.md,
    paddingLG: designTokens.spacing.lg,
    paddingSM: designTokens.spacing.sm,
    paddingXS: designTokens.spacing.xs,
    
    margin: designTokens.spacing.md,
    marginLG: designTokens.spacing.lg,
    marginSM: designTokens.spacing.sm,
    marginXS: designTokens.spacing.xs,
    
    // 阴影
    boxShadow: designTokens.shadows.md,
    boxShadowSecondary: designTokens.shadows.sm,
    
    // 布局
    colorBgLayout: designTokens.colors.bgLayout,
    colorBgContainer: designTokens.colors.bgContainer,
    colorBgElevated: designTokens.colors.bgElevated,
    colorBgSpotlight: designTokens.colors.bgSpotlight,
    
    // 文本
    colorText: designTokens.colors.textPrimary,
    colorTextSecondary: designTokens.colors.textSecondary,
    colorTextTertiary: designTokens.colors.textTertiary,
    colorTextQuaternary: designTokens.colors.textQuaternary,
    
    // 边框
    colorBorder: designTokens.colors.borderPrimary,
    colorBorderSecondary: designTokens.colors.borderSecondary,
    
    // 动画
    motionDurationFast: designTokens.motion.duration.fast,
    motionDurationMid: designTokens.motion.duration.normal,
    motionDurationSlow: designTokens.motion.duration.slow,
  },
  components: {
    Layout: {
      headerBg: designTokens.colors.bgContainer,
      siderBg: '#001529',
      bodyBg: designTokens.colors.bgLayout,
      headerHeight: 64,
      headerPadding: '0 24px',
    },
    Menu: {
      darkItemBg: '#001529',
      darkSubMenuItemBg: '#000c17',
      darkItemSelectedBg: designTokens.colors.primary,
      darkItemHoverBg: 'rgba(255, 255, 255, 0.06)',
      itemHeight: 40,
      itemMarginInline: 4,
    },
    Button: {
      borderRadius: designTokens.borderRadius.md,
      controlHeight: 32,
      controlHeightLG: 40,
      controlHeightSM: 24,
      paddingInline: designTokens.spacing.md,
      paddingInlineLG: designTokens.spacing.lg,
      paddingInlineSM: designTokens.spacing.sm,
    },
    Card: {
      borderRadius: designTokens.borderRadius.lg,
      paddingLG: designTokens.spacing.lg,
      headerBg: 'transparent',
    },
    Table: {
      borderRadius: designTokens.borderRadius.lg,
      headerBg: '#fafafa',
      headerSplitColor: designTokens.colors.borderSecondary,
    },
    Form: {
      itemMarginBottom: designTokens.spacing.lg,
      verticalLabelPadding: `0 0 ${designTokens.spacing.sm}px`,
    },
    Input: {
      borderRadius: designTokens.borderRadius.md,
      controlHeight: 32,
      controlHeightLG: 40,
      controlHeightSM: 24,
      paddingInline: designTokens.spacing.sm,
    },
    Select: {
      borderRadius: designTokens.borderRadius.md,
      controlHeight: 32,
      controlHeightLG: 40,
      controlHeightSM: 24,
    },
    Modal: {
      borderRadius: designTokens.borderRadius.lg,
      headerBg: 'transparent',
    },
    Drawer: {
      borderRadius: designTokens.borderRadius.lg,
    },
    Notification: {
      borderRadius: designTokens.borderRadius.lg,
    },
    Message: {
      borderRadius: designTokens.borderRadius.lg,
    },
    Tooltip: {
      borderRadius: designTokens.borderRadius.md,
    },
    Popover: {
      borderRadius: designTokens.borderRadius.lg,
    },
  },
}

// 暗黑主题设计令牌
export const darkDesignTokens = {
  ...designTokens,
  colors: {
    ...designTokens.colors,
    // 暗黑模式文本色
    textPrimary: 'rgba(255, 255, 255, 0.88)',
    textSecondary: 'rgba(255, 255, 255, 0.65)',
    textTertiary: 'rgba(255, 255, 255, 0.45)',
    textQuaternary: 'rgba(255, 255, 255, 0.25)',
    
    // 暗黑模式背景色
    bgLayout: '#000000',
    bgContainer: '#141414',
    bgElevated: '#1f1f1f',
    bgSpotlight: '#262626',
    
    // 暗黑模式边框色
    borderSecondary: '#303030',
    borderPrimary: '#434343',
  }
}

// 暗黑主题配置
export const darkThemeConfig: ThemeConfig = {
  ...themeConfig,
  algorithm: theme.darkAlgorithm,
  token: {
    ...themeConfig.token,
    // 暗黑模式背景
    colorBgLayout: darkDesignTokens.colors.bgLayout,
    colorBgContainer: darkDesignTokens.colors.bgContainer,
    colorBgElevated: darkDesignTokens.colors.bgElevated,
    colorBgSpotlight: darkDesignTokens.colors.bgSpotlight,
    
    // 暗黑模式文本
    colorText: darkDesignTokens.colors.textPrimary,
    colorTextSecondary: darkDesignTokens.colors.textSecondary,
    colorTextTertiary: darkDesignTokens.colors.textTertiary,
    colorTextQuaternary: darkDesignTokens.colors.textQuaternary,
    
    // 暗黑模式边框
    colorBorder: darkDesignTokens.colors.borderPrimary,
    colorBorderSecondary: darkDesignTokens.colors.borderSecondary,
  },
  components: {
    ...themeConfig.components,
    Layout: {
      ...themeConfig.components?.Layout,
      headerBg: darkDesignTokens.colors.bgElevated,
      bodyBg: darkDesignTokens.colors.bgLayout,
    },
    Card: {
      ...themeConfig.components?.Card,
      headerBg: 'transparent',
    },
    Table: {
      ...themeConfig.components?.Table,
      headerBg: darkDesignTokens.colors.bgSpotlight,
    },
  },
}

// 响应式断点配置
export const breakpoints = {
  xs: 480,
  sm: 576,
  md: 768,
  lg: 992,
  xl: 1200,
  xxl: 1600,
}

// 响应式工具函数
export const responsive = {
  // 获取当前屏幕尺寸类型
  getCurrentBreakpoint(): keyof typeof breakpoints {
    const width = window.innerWidth
    if (width < breakpoints.xs) return 'xs'
    if (width < breakpoints.sm) return 'sm'
    if (width < breakpoints.md) return 'md'
    if (width < breakpoints.lg) return 'lg'
    if (width < breakpoints.xl) return 'xl'
    return 'xxl'
  },
  
  // 检查是否为移动设备
  isMobile(): boolean {
    return window.innerWidth < breakpoints.md
  },
  
  // 检查是否为平板设备
  isTablet(): boolean {
    return window.innerWidth >= breakpoints.md && window.innerWidth < breakpoints.lg
  },
  
  // 检查是否为桌面设备
  isDesktop(): boolean {
    return window.innerWidth >= breakpoints.lg
  }
}

// 主题切换工具
export class ThemeManager {
  private static instance: ThemeManager
  private currentTheme: 'light' | 'dark' = 'light'
  private listeners: Array<(theme: 'light' | 'dark') => void> = []
  private mediaQuery: MediaQueryList

  constructor() {
    // 监听系统主题变化
    this.mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    this.mediaQuery.addEventListener('change', this.handleSystemThemeChange.bind(this))
  }

  static getInstance(): ThemeManager {
    if (!ThemeManager.instance) {
      ThemeManager.instance = new ThemeManager()
    }
    return ThemeManager.instance
  }

  getCurrentTheme(): 'light' | 'dark' {
    return this.currentTheme
  }

  setTheme(theme: 'light' | 'dark'): void {
    this.currentTheme = theme
    localStorage.setItem('theme', theme)
    
    // 更新HTML根元素的data-theme属性
    document.documentElement.setAttribute('data-theme', theme)
    
    // 更新CSS变量
    this.updateCSSVariables(theme)
    
    // 通知监听器
    this.listeners.forEach(listener => listener(theme))
  }

  getThemeConfig(): ThemeConfig {
    return this.currentTheme === 'dark' ? darkThemeConfig : themeConfig
  }

  getDesignTokens() {
    return this.currentTheme === 'dark' ? darkDesignTokens : designTokens
  }

  initTheme(): void {
    const savedTheme = localStorage.getItem('theme') as 'light' | 'dark' | null
    if (savedTheme) {
      this.setTheme(savedTheme)
    } else {
      // 检测系统主题偏好
      const prefersDark = this.mediaQuery.matches
      this.setTheme(prefersDark ? 'dark' : 'light')
    }
  }

  // 添加主题变化监听器
  addThemeChangeListener(listener: (theme: 'light' | 'dark') => void): void {
    this.listeners.push(listener)
  }

  // 移除主题变化监听器
  removeThemeChangeListener(listener: (theme: 'light' | 'dark') => void): void {
    const index = this.listeners.indexOf(listener)
    if (index > -1) {
      this.listeners.splice(index, 1)
    }
  }

  // 处理系统主题变化
  private handleSystemThemeChange(e: MediaQueryListEvent): void {
    // 只有在用户没有手动设置主题时才跟随系统
    const savedTheme = localStorage.getItem('theme')
    if (!savedTheme) {
      this.setTheme(e.matches ? 'dark' : 'light')
    }
  }

  // 更新CSS变量
  private updateCSSVariables(theme: 'light' | 'dark'): void {
    const tokens = theme === 'dark' ? darkDesignTokens : designTokens
    const root = document.documentElement
    
    // 设置颜色变量
    Object.entries(tokens.colors).forEach(([key, value]) => {
      if (typeof value === 'string') {
        root.style.setProperty(`--color-${key}`, value)
      } else if (typeof value === 'object') {
        Object.entries(value).forEach(([subKey, subValue]) => {
          root.style.setProperty(`--color-${key}-${subKey}`, subValue as string)
        })
      }
    })
    
    // 设置间距变量
    Object.entries(tokens.spacing).forEach(([key, value]) => {
      root.style.setProperty(`--spacing-${key}`, `${value}px`)
    })
    
    // 设置圆角变量
    Object.entries(tokens.borderRadius).forEach(([key, value]) => {
      root.style.setProperty(`--border-radius-${key}`, typeof value === 'number' ? `${value}px` : value)
    })
    
    // 设置字体变量
    root.style.setProperty('--font-family', tokens.typography.fontFamily)
    Object.entries(tokens.typography.fontSizes).forEach(([key, value]) => {
      root.style.setProperty(`--font-size-${key}`, `${value}px`)
    })
  }

  // 获取响应式配置
  getResponsiveConfig() {
    const currentBreakpoint = responsive.getCurrentBreakpoint()
    
    return {
      breakpoint: currentBreakpoint,
      isMobile: responsive.isMobile(),
      isTablet: responsive.isTablet(),
      isDesktop: responsive.isDesktop(),
      // 根据屏幕尺寸调整组件大小
      componentSize: responsive.isMobile() ? 'small' : responsive.isTablet() ? 'middle' : 'large',
      // 根据屏幕尺寸调整侧边栏
      siderCollapsed: responsive.isMobile(),
      // 根据屏幕尺寸调整表格
      tableSize: responsive.isMobile() ? 'small' : 'middle',
      // 根据屏幕尺寸调整表单
      formLayout: responsive.isMobile() ? 'vertical' : 'horizontal',
    }
  }
}